<template>
  <a-card :title="!route.query.id ? '产品添加' : '产品修改'">
    <a-form
      :model="formState"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      @finish="onFinish"
      autocomplete="off"
    >
      <a-form-item
        label="产品标题"
        :rules="[{ required: true, message: '请输入产品名称' }]"
      >
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item
        label="产品简介"
        :rules="[{ required: true, message: '请输入产品简介' }]"
      >
        <a-input v-model:value="formState.desc"
      /></a-form-item>
      <a-form-item
        label="产品内容"
        :rules="[{ required: true, message: '请输入产品内容' }]"
      >
        <WangEditor v-model:value.lazy="formState.content" />
      </a-form-item>

      <a-form-item
        label="产品封面"
        :rules="[{ required: true, message: '请上传产品封面图' }]"
      >
        <Upload v-model:value.lazy="formState.img"></Upload>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button type="primary" html-type="submit">
          {{ route.query.id ? "修改" : "创建" }}
        </a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import Upload from "@/components/Upload";
import WangEditor from "@/components/WangEditor";
import { productAdd, productEdit, productDetail } from "@/api/product";
import { Form } from "ant-design-vue";

const router = useRouter();
const route = useRoute();
const labelCol = { span: 4 };
const wrapperCol = { span: 20 };

const formState = ref({
  name: "", // 标题
  desc: "", // 描述
  img: "", // 图片
  type: "", // 类型
  content: "", // 简介
});
const getProductDetail = async () => {
  const { id } = route.query;
  const { msg, success, data } = await productDetail({ _id: id });
  if (success) {
    formState.value = {
      name: data.name,
      desc: data.desc,
      img: data.img,
      type: data.type,
      content: data.content,
    };
  } else {
    message.error(msg);
  }
};

onMounted(() => {
  if (route.query.id) {
    getProductDetail();
  }
});

// 提交
const onFinish = async () => {
  const { success, msg } = !route.query.id
    ? await productAdd(formState.value)
    : await productEdit({ ...formState.value, _id: route.query.id });
  if (success) {
    message.success(msg);
    router.push({ path: "/product-manage" });
  } else {
    message.error(msg);
  }
};
</script>


